package cog.support.util.handle.dynamic;

import cog.support.util.common.model.MapRecord;
import cog.support.util.handle.IProcessHandling;

import java.util.HashMap;
import java.util.Map;

/**
 * 动态的流程处理器
 *
 * @author 陈杰
 * @since 2016年9月12日 00:53:51
 * @version v0.1
 *
 * Copyright ChenJie(chenjie_java@aliyun.com) 2016年9月12日 00:53:51
 */
public abstract class AbstractDynamicProcessHandling implements IProcessHandling{

    /**
     * 当前处理器名称
     * */
    protected String handleName;

    /**
     * 处理器List
     * */
    private static Map<String,IProcessHandling> handlingMap = new HashMap<>();

    /**
     * 下一个处理器
     * */
    private IProcessHandling nextHandle;

    public AbstractDynamicProcessHandling(String handleName){
        this.handleName = handleName;
        this.registerHandle(this);
    }

    public AbstractDynamicProcessHandling(String handleName,IProcessHandling nextHandle){
        this.handleName = handleName;
        this.nextHandle = nextHandle;
        this.registerHandle(this);
    }

    @Override
    public void linkNextHandle(IProcessHandling handling) {
        this.nextHandle = handling;
    }

    @Override
    public Object nextHandle(MapRecord<String,Object> parameters) throws Exception {
        return this.nextHandle.handle(parameters);
    }

    /**
     * 通过处理器名称跳转下个处理器
     * */
    protected Object nextHandle(String handleName,MapRecord<String,Object> parameters) throws Exception {
        IProcessHandling next = AbstractDynamicProcessHandling.handlingMap.get(handleName);
        if(next != null) return next.handle(parameters);
        return null;
    }

    private void registerHandle(IProcessHandling nextHandle){
        if(nextHandle instanceof AbstractDynamicProcessHandling){
            AbstractDynamicProcessHandling handle = (AbstractDynamicProcessHandling)nextHandle;
            AbstractDynamicProcessHandling.handlingMap.put(handle.handleName,handle);
        }
    }
}
